package com.mengwen.backstage.controller;


import com.mengwen.backstage.manager.MenuManager;
import com.mengwen.backstage.pojo.Partner;
import com.mengwen.backstage.service.AdminService;
import com.mengwen.backstage.service.PartnerService;
import com.mengwen.backstage.util.WeixinUtil;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;

/**
 * 微信授权登录
 */
@Controller
public class WeiXinOauth {

    private String fromIP;

    @Autowired
    PartnerService partnerService;

    @Autowired
    AdminService adminService;

    @Autowired
    RedisTemplate redisTemplate;

    @RequestMapping("/login")
    public String aaa(){
        System.out.println("iadiauhdaihdaihdiaudaiuda");return "partner_page";
    }

//    @RequestMapping("/mengwen/oauth")
//    public void oauth(HttpServletResponse response) throws IOException {
//        System.out.println("进来到这里了");
//        String path = MenuManager.REAL_URL + "/mengwen/invoke";
//        System.out.println(path);
//        path = URLEncoder.encode(path,"UTF-8");
//
//
//        String url = "https://open.weixin.qq.com/connect/oauth2/authorize?"
//               + "appid="+MenuManager.appId
//               + "&redirect_uri="+ path
//               + "&response_type=code"
//               + "&scope=snsapi_userinfo"
//               +"&state=mwoauth#wechat_redirect";
//
//        response.sendRedirect(url);
//
//        System.out.println(url);
//
//    }



    @RequestMapping("/mengwen/oauth/userInfo")
    public void oauthUserInfo(HttpServletResponse response) throws IOException {
//        System.out.println("进来到这里了");
        String path = MenuManager.REAL_URL + "/mengwen/userInfo/invoke";
//        System.out.println(path);
        path = URLEncoder.encode(path,"UTF-8");


        String url = "https://open.weixin.qq.com/connect/oauth2/authorize?"
                + "appid="+MenuManager.appId
                + "&redirect_uri="+ path
                + "&response_type=code"
                + "&scope=snsapi_userinfo"
                +"&state=mwoauth#wechat_redirect";

        response.sendRedirect(url);


    }

//    @RequestMapping("/mengwen/invoke")
//    public void aouthInvoke(HttpServletRequest request){
//
//        String code = request.getParameter("code");
//        String state = request.getParameter("state");
//
////        System.out.println("code:" + code);
////        System.out.println("state:" + state);
//
//
//        // 通过code换取网页授权的accesstoken  这不同于调用微信内部api的那个token
//        // 认证服务器
//        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?"
//               + "appid=" + MenuManager.appId
//               + "&secret=" + MenuManager.appSecret
//               + "&code=" + code
//               + "&grant_type=authorization_code";
//
//
//        JSONObject accessTokenAndOpenidjsonObject = WeixinUtil.httpRequest(url, "POST", null);
//
//        System.out.println(accessTokenAndOpenidjsonObject.toString());
//
//
//        // 用accessToken 和 openId 获取用户的信息
//        String urlUserInfo = "https://api.weixin.qq.com/sns/userinfo?"
//                +"access_token=" + accessTokenAndOpenidjsonObject.getString("access_token")
//                +"&openid=" + accessTokenAndOpenidjsonObject.getString("openid")
//                +"&lang=zh_CN";
//
//        JSONObject userInfoJsonObject = WeixinUtil.httpRequest(urlUserInfo, "GET", null);
//
//        System.out.println("看这里=============================================");
//        // 授权成功就把openid注入进表中，当账号密码登录的时候则将初次登录完成的标识符state置成1
//        System.out.println(userInfoJsonObject.toString());
//    }


    //
    //  https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
    //

    @RequestMapping("/mengwen/userInfo/invoke")
    public String aouthUserInfoInvoke(HttpServletRequest request, Model model){

        String code = request.getParameter("code");
//        String state = request.getParameter("state");

//        System.out.println("code:" + code);
//        System.out.println("state:" + state);


        // 通过code换取网页授权的accesstoken  这不同于调用微信内部api的那个token
        // 认证服务器
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?"
                + "appid=" + MenuManager.appId
                + "&secret=" + MenuManager.appSecret
                + "&code=" + code
                + "&grant_type=authorization_code";


        JSONObject accessTokenAndOpenidjsonObject = WeixinUtil.httpRequest(url, "POST", null);

//        System.out.println(accessTokenAndOpenidjsonObject.toString());

        Partner partner = partnerService.findByOpenid(accessTokenAndOpenidjsonObject.getString("openid"));

        if (partner != null) {
            System.out.println("是已登陆过的合伙人，直接跳转合伙人页面");
            model.addAttribute("partner",partner);
            return "partner_page";
        }

        // 不是合伙人和管理员，跳转登录分流 入口
        System.out.println("啥也不是啊啊啊啊啊啊啊啊啊啊 啊啊啊啊啊啊啊啊  啊啊啊啊");



        // 用accessToken 和 openId 获取用户的信息
        String urlUserInfo = "https://api.weixin.qq.com/sns/userinfo?"
                +"access_token=" + accessTokenAndOpenidjsonObject.getString("access_token")
                +"&openid=" + accessTokenAndOpenidjsonObject.getString("openid")
                +"&lang=zh_CN";

        JSONObject userInfoJsonObject = WeixinUtil.httpRequest(urlUserInfo, "GET", null);

        System.out.println("看这里=============================================");
        System.out.println(userInfoJsonObject.toString());





        return "login_door";
    }


    @RequestMapping("/fromip")
    public void getIP(HttpServletRequest request){
        String fromIp = request.getParameter("ip");
        System.out.println("==================================================");
        System.out.println("这是ip地址：" + fromIp);
        System.out.println("==================================================");

    }



}
